//
//  ViewController.swift
//  SelfStopWatch
//
//  Created by panda on 17/3/16.
//  Copyright © 2017年 panda. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    //MARK: - 参数
    var count : Int = 0 {//总的计数
        willSet(value) {
            showNumV.bigStr = showTime(count: value)
        }
    }
    
    var smallCount : Int = 0 {//时间差计数
        willSet(value) {
            showNumV.smallStr = showTime(count: value)
        }
    }
    var dataArr : [String] = []
    var BigTimer : Timer?   //总的计时器
    var smallTimer : Timer? //时间差计时器
    //是否在计时中
    var isStar : Bool = false {
        willSet(value) {
            
            if value {
                resetBtn.isEnabled = value
                showNumV.isStar = value
                
                starStatus()
                if !isFirstStar {
                    BigTimer?.fireDate = NSDate.distantPast
                    smallTimer?.fireDate = NSDate.distantPast
                }
            }else {
                BigTimer?.fireDate = NSDate.distantFuture
                smallTimer?.fireDate = NSDate.distantFuture
                stopStatus()
            }
        }
    }
    //是否第一次点击开始
    var isFirstStar : Bool = true {
        willSet(value) {
            if !value {
                BigTimer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true);
            }
        }
    }
    
    //MARK: - 生命周期
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        view.backgroundColor = UIColor.black
        
        view.addSubview(showNumV)
        view.addSubview(starBtn)
        view.addSubview(resetBtn)
        view.addSubview(tableV)
        
        
    }
    
    override func viewDidLayoutSubviews() {
         super.viewDidLayoutSubviews()
        addConstraint()
    }
    
    //MARK: - 点击事件
    func starBtnAction(sender: UIButton) {
        if isFirstStar {
            isFirstStar = false
        }
        
        isStar = !isStar
    }
    
    func resetBtnAction(sender: UIButton) {
        if isStar {
            //在计时状态下,获取到当前记录时间
            smallCount = 0
            smallTimer?.invalidate()
            smallTimer = nil
            smallTimer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(updateSmallTimer), userInfo: nil, repeats: true);
            
            dataArr.append(showTime(count: count))
            tableV.reloadData()
            
        }else {
            //如果在停止状态,点击resetBtn则是复位功能,计数清零,resetBtn不能点击
            
            originalState(isEnable: false)
        }
    }
    
    @objc private func updateTimer() {
        count += 1;
    }
    
    @objc private func updateSmallTimer() {
        smallCount += 1
    }
    
    //MARK: - 私有方法
    //计时停止时按钮的状态
    private func stopStatus() {
        resetBtn.setTitle("复位", for: UIControlState.normal)
        starBtn.backgroundColor = UIColor.cyan
        starBtn.setTitle("启动", for: UIControlState.normal)
        starBtn.setTitleColor(UIColor.white, for: UIControlState.normal)
    }
    //计时启动时按钮的状态
    private func starStatus() {
        resetBtn.backgroundColor = UIColor.gray
        resetBtn.setTitleColor(UIColor.white, for: UIControlState.normal)
        resetBtn.setTitle("计次", for: UIControlState.normal)
        resetBtn.alpha = 1.0
        starBtn.setTitle("停止", for: UIControlState.normal)
        starBtn.backgroundColor = UIColor.red
        starBtn.setTitleColor(UIColor.black, for: UIControlState.normal)
    }
    //复位后,回到原始状态
    private func originalState(isEnable: Bool) {
        starBtn.backgroundColor = UIColor.cyan
        starBtn.setTitle("启动", for: UIControlState.normal)
        starBtn.setTitleColor(UIColor.white, for: UIControlState.normal)
        resetBtn.setTitle("计次", for: UIControlState.normal)
        resetBtn.alpha = 0.3
        resetBtn.isEnabled = isEnable
        count = 0
        smallCount = 0
        isFirstStar = true
        
        BigTimer?.invalidate()
        BigTimer = nil;
        smallTimer?.invalidate()
        smallTimer = nil;
        showNumV.isStar = false
        
        dataArr.removeAll()
        tableV.reloadData()
    }
    
    //计时器显示
    private func showTime(count: Int) -> String {
        let min = count / 100 / 60
        let sec = count / 100 % 60
        let point = count % 100
        let showStr = String(format: "%02d:%02d.%02d", min, sec, point)
        return showStr
        
    }
    
    
    //MARK: - addConstraint
    func addConstraint() {
        showNumV.frame = CGRect(x: 0, y: 64, width: 375, height: 100)
        resetBtn.frame = CGRect(x: (375/2 - 50)/2, y: showNumV.frame.maxY + 20, width: 60, height: 60)
        starBtn.frame = CGRect(x: resetBtn.frame.minX*3+resetBtn.frame.width, y: resetBtn.frame.minY, width: resetBtn.frame.width, height: resetBtn.frame.height)
        starBtn.layer.cornerRadius = 30
        resetBtn.layer.cornerRadius = 30
        tableV.frame = CGRect(x: 0, y: resetBtn.frame.maxY + 20, width: 375, height: UIScreen.main.bounds.height - resetBtn.frame.height)
    }

    //MARK: - 懒加载
    fileprivate lazy var tableV : UITableView = {
        let tableV = UITableView()
        tableV.delegate = self
        tableV.dataSource = self
        tableV.separatorStyle = .none
        tableV.backgroundColor = UIColor.white
        return tableV;
    }()
    
    fileprivate lazy var starBtn : UIButton = {
        let btn = UIButton(type: UIButtonType.custom)
        btn.backgroundColor = UIColor.cyan
        btn.setTitle("启动", for: UIControlState.normal)
        btn.setTitleColor(UIColor.white, for: UIControlState.normal)
        btn.addTarget(self, action: #selector(starBtnAction(sender:)), for: UIControlEvents.touchUpInside)
        return btn;
    }()
    
    fileprivate lazy var resetBtn : UIButton = {
       let btn = UIButton(type: UIButtonType.custom)
        btn.isEnabled = false
        btn.alpha = 0.3
        btn.backgroundColor = UIColor.darkGray
        btn.setTitle("计次", for: UIControlState.normal)
        btn.setTitleColor(UIColor.gray, for: UIControlState.normal)
        btn.addTarget(self, action: #selector(resetBtnAction(sender:)), for: UIControlEvents.touchUpInside)
        return btn;
    }()
    
    fileprivate lazy var showNumV : ShowNumberView = {
        let v = ShowNumberView()
        v.backgroundColor = UIColor.clear
        return v;
    }()

}

// MARK: - UITableViewDelegate
extension ViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellId = "cellID"
        var cell = tableView.dequeueReusableCell(withIdentifier: cellId)
        if cell == nil {
            cell = UITableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellId)
        }
        cell?.textLabel?.text = dataArr[indexPath.row]
        
        return cell!
    }
}

